package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"lz/config"
	"lz/forms"
	"net/http"
	"regexp"
	"strings"
)

type ModelRespon struct {
	Total int64 `json:"total"`
}

func LqHtm(c *gin.Context) {

	var htm forms.HtmForm
	if err := c.ShouldBindJSON(&htm); err != nil {
		zap.S().Errorf("验证数据出错:%v", err)
		HandleValidator(err, c)
		return
	}
	returnMap := make(map[string]interface{}, 0)
	rule := make(map[string]bool, 0)
	//1检测是否存在字符串存在则设置分类为true,否则为false
	for k, v := range config.RuleConfig.Rule {

		for ruleK, ruleV := range v {

			if ruleV.(bool) {
				index := strings.Index(htm.Htm, ruleK)
				if index > -1 {
					rule[k] = true
					break
				}
			}
		}
		//如果没有检测到想要的结果用key再去检查一次
		v, ok := rule[k]
		if !ok || v == false {
			index := strings.Index(htm.Htm, k)
			if index > -1 {
				rule[k] = true
				break
			} else {
				rule[k] = false
			}
		}

	}
	returnMap["one"] = rule
	r, _ := json.Marshal(rule)
	zap.S().Infof("第一步检测数据为：%v", string(r))

	//2提取类型对应的名称
	tirmHtm := trimHtml(htm.Htm)
	str := strings.Replace(tirmHtm, "\n", "84596", -1)
	str = strings.Replace(str, " ", "", -1)

	fmt.Println(str)
	//str = strings.Replace(str, "、", "84596", -1)
	//str = strings.Replace(tirmHtm, "\n", "84596", -1)
	str = strings.Replace(str, ":", "84596", -1)
	str = strings.Replace(str, ",", "84596", -1)
	str = strings.Replace(str, "：", "84596", -1)
	str = strings.Replace(str, "，", "84596", -1)
	str = strings.Replace(str, " ", "84596", -1)

	arr := strings.Split(str, "84596")
	m := make(map[string]interface{}, 0)

	for k, v := range config.RuleConfig.RuleName {
		mm := make(map[string]string, 0)
		for kk, _ := range v {

			for ak, av := range arr {
				if strings.Replace(av, ":", "", -1) == kk || strings.Index(av, kk) > -1 {

					if (ak + 1) > len(arr) {
						continue
					}
					mm[kk] += arr[ak+1] + ","
				}
			}
			mm[kk] = strings.TrimRight(mm[kk], ",")
		}
		m[k] = mm
	}
	returnMap["two"] = m
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": returnMap,
	})
}

func trimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")
	return strings.TrimSpace(src)
}
